package com.apps.diet.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.apps.diet.domain.UserMealTypes;

@Repository
public class UserMealTypesDaoImpl extends AbstractDAO implements IUserMealTypesDao {

	Logger logger = Logger.getLogger(UserMealTypesDaoImpl.class);

	@SuppressWarnings("static-access")
	@Override
	public List<UserMealTypes> getUserMealTypes (int searchString) {
		SessionFactory sf = hbUtil.getSessionFactory();
        Session session = sf.openSession();
        		
        Criteria c = session.createCriteria(UserMealTypes.class);

        if (searchString == 0){
//        	Do nothing; Return all results
        }else{
        	c.add(Restrictions.like("userId", "%"+searchString+"%"));
        }

        List<UserMealTypes> userMealTypesList = c.list();
        logger.debug("Total result found: "+userMealTypesList.size());
        session.close();
        
        return userMealTypesList;
	}
	
	@Override
	public boolean createUserMealTypes (UserMealTypes userMealTypes) {
		SessionFactory sf = hbUtil.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();

        try {
        	session.save(userMealTypes);
        	session.getTransaction().commit();
        }catch(Exception e){
        	session.getTransaction().rollback();
        	logger.error(e.getMessage());
        	return false;
        }finally{
            session.close();
        }
    	return true;
	}

	@Override
	public boolean updateUserMealTypes (UserMealTypes userMealTypes) {
		SessionFactory sf = hbUtil.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();

        try {
        	session.update(userMealTypes);
        	session.getTransaction().commit();
        }catch(Exception e){
        	session.getTransaction().rollback();
        	logger.error(e.getMessage());
        	return false;
        }finally{
            session.close();
        }
   	
        return true;
	}

	@Override
	public boolean deleteUserMealTypes (int userMealTypesId) throws Exception {
		SessionFactory sf = hbUtil.getSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();

        try{
        	UserMealTypes UserMealTypes = (UserMealTypes) session.get(UserMealTypes.class, userMealTypesId);
    		session.delete(UserMealTypes);
    		session.getTransaction().commit();
        }catch(Exception e){
        	session.getTransaction().rollback();
        	logger.error(e.getMessage());
        	throw e;
        }finally{
            session.close();
        }

        return true;
	}
}
